package com.znsb.msfq.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.mobstat.StatService;
import com.znsb.msfq.BaseFragment;
import com.znsb.msfq.R;
import com.znsb.msfq.adapter.H2ShopRVAdapter;
import com.znsb.msfq.adapter.comadapter.CommonAdapter;
import com.znsb.msfq.adapter.comadapter.ViewHolder;
import com.znsb.msfq.app.ZnsbApp;
import com.znsb.msfq.bean.H1genreItemBean;
import com.znsb.msfq.bean.H2ShopItemBean;
import com.znsb.msfq.broadcast.IListener;
import com.znsb.msfq.broadcast.ListenerManager;
import com.znsb.msfq.utils.GsonUtils;
import com.znsb.msfq.utils.HttpUtils;
import com.znsb.msfq.utils.JsonResult;
import com.znsb.msfq.utils.LogUtils;
import com.znsb.msfq.utils.NetworkAddress;
import com.znsb.msfq.utils.OverallData;
import com.znsb.msfq.utils.ResponseUtils;
import com.znsb.msfq.view.EndLessOnScrollListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * 名称：分类
 * 创建时间：2016/10/20.
 * 作者：杨广
 * 手机号：17382373271
 * 说明：
 */

public class Home2Fragment extends BaseFragment implements IListener {

    @Bind(R.id.h2f_lv_listview)
    ListView h2fLvListview;
    @Bind(R.id.h2_list_recyler_view)
    RecyclerView listRecylerView;
    @Bind(R.id.title_back)
    TextView titleBack;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.h2_list_swiperefresh_layout)
    SwipeRefreshLayout listSwiperefreshLayout;
    private CommonAdapter<H1genreItemBean> adapter;
    // 用来控制CheckBox的选中状况
    private HashMap<Integer, Boolean> isSelected;
    private int indexed = 0;

    private List<H1genreItemBean> list;
    private List<H2ShopItemBean> lists;

    private H2ShopRVAdapter h2ShopRVAdapter;
    private GridLayoutManager layoutManager;
    private int pageNo = 1;

    private Handler hander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 300:
                    SetLists();
                    GetGoods(list.get(indexed).getId(), pageNo);
                    break;
                case 200:
//                    SetList();
//                    h2ShopRVAdapter.updateList(lists);
                    h2ShopRVAdapter.notifyDataSetChanged();
                    break;
            }

        }
    };

    @Override
    protected int getlayoutView() {
        return R.layout.frag_home2;
    }

    @Override
    protected void initView(View view) {
        titleBack.setVisibility(View.GONE);
        titleText.setText(getResources().getString(R.string.home_tab2shop));
    }

    @Override
    protected void initData() {


        /**
         * 列表属性配置
         */
        listSwiperefreshLayout.setColorSchemeResources(R.color.blueStatus);

        layoutManager = new GridLayoutManager(getActivity(), 3);
        listRecylerView.setLayoutManager(layoutManager);
        listSwiperefreshLayout.setOnRefreshListener(onRefresh);

        list = new ArrayList<>();
        lists = new ArrayList<>();
        //注册监听器
        ListenerManager.getInstance().registerListtener(this);
        indexed = OverallData.getIndex();
        isSelected = new HashMap<>();
        h2ShopRVAdapter = new H2ShopRVAdapter(getActivity(), lists);
        listRecylerView.setAdapter(h2ShopRVAdapter);
        /**
         * 下拉加载更多
         */
        listRecylerView.addOnScrollListener(new EndLessOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                pageNo++;
                GetGoods(list.get(indexed).getId(), pageNo);
            }
        });

        GetCategorys();
    }


    private void SetLists() {
        adapter = new CommonAdapter<H1genreItemBean>(getActivity(), R.layout.item_home2_shoptype, list) {
            @Override
            protected void fillItemData(ViewHolder viewHolder, int position, H1genreItemBean item) {
                try {

                    viewHolder.setClick(R.id.ihf_cb_checkbox, isSelected.get(position));
                    //设置text
                    viewHolder.setText(R.id.ihf_cb_checkbox, item.title);
                } catch (Exception e) {
                }

            }
        };
        h2fLvListview.setAdapter(adapter);
        h2fLvListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position != indexed) {
                    lists.clear();
                    isSelected.put(indexed, false);
                    isSelected.put(position, true);
                    adapter.notifyDataSetChanged();
                    indexed = position;
                    pageNo = 1;
                    GetGoods(list.get(position).getId(), pageNo);
                }
            }
        });
        h2fLvListview.setSelection(indexed);//ListView滚动到指定的位置
    }

    private void SetList() {

//        h2ShopRVAdapter.set
//        h2fGvGridview.setAdapter(new CommonAdapter<H2ShopItemBean>(getActivity(), R.layout.item_home2_shop, lists) {
//            @Override
//            protected void fillItemData(ViewHolder viewHolder, int position, H2ShopItemBean item) {
//                // 设置图片
//                viewHolder.setImageByUrl(R.id.h2f_iv_shopimg, item.logo);
//                viewHolder.setImageByUrl(R.id.h2f_iv_img, item.sourceLogo);
//                //设置text
//                viewHolder.setText(R.id.h2f_tv_shopname, item.categoryName);
//                viewHolder.setText(R.id.h2f_tv_shoppice, item.price);
//            }
//        });

//        h2fGvGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if (lists.size() > position) {
//                    Bundle bundle = new Bundle();
//                    bundle.putInt("ids", lists.get(position).id);
//                    ActivityUtil.next(getActivity(), CommodityDetailsActivity.class, bundle);
//                }
//
//            }
//        });


    }

    /**
     * 下拉刷新
     */
    private SwipeRefreshLayout.OnRefreshListener onRefresh = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    pageNo = 1;
                    lists.clear();
                    if (list.size()>indexed){
                        GetGoods(list.get(indexed).getId(), pageNo);
                    }
                    listSwiperefreshLayout.setRefreshing(false);
                }
            }, 1000);
        }
    };

    @Override
    protected void clickListener(View view) {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate recyler_divider fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void notifyAllActivity(int index) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getId() == index) {
                index = i;
            }
        }
        if (index != indexed) {
            isSelected.put(indexed, false);
            isSelected.put(index, true);
            adapter.notifyDataSetChanged();
            indexed = index;
            h2fLvListview.setSelection(indexed);//ListView滚动到指定的位置
        }
    }


    //商品分类列表
    public void GetCategorys() {

        Map<String, Object> maps = new HashMap<>();
//        maps.put("isRecommend", 1);//是否推荐分类，0不推荐，1推荐，不传默认不推荐
//        maps.put("pageSize", 10);//一页多少条，不传递默认10条
        HttpUtils.getInstance(getActivity()).postAsnyRequest(NetworkAddress.Categorys, HttpUtils.getMaps(maps), new ResponseUtils() {
            @Override
            public void onSucceed(String code, JSONObject request) {
                try {
                    LogUtils.i("", ">>>>>>h2GetCategorys" + request);
                    JSONArray dataList = JsonResult.getJSONArray(request, "dataList");
                    for (int i = 0; i < dataList.length(); i++) {
                        JSONObject jsonObject = dataList.getJSONObject(i);
                        try {
                            H1genreItemBean h1genreItemBean = (H1genreItemBean) GsonUtils.getGsonData(H1genreItemBean.class, jsonObject.toString());
                            list.add(h1genreItemBean);
                            isSelected.put(i, false);
                        } catch (Exception e) {
                            LogUtils.i("", ">>>>>>e" + e);
                        }
                    }
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getId() == indexed) {
                            indexed = i;
                            isSelected.put(i, true);
                        }
                    }
                    if (indexed == -100) {
                        indexed = 0;
                        isSelected.put(0, true);
                    }

                } catch (Exception e) {
                    LogUtils.i("", ">>>>>>e" + e);
                }
                hander.sendEmptyMessage(300);
            }

            @Override
            public void onFailure(String result) {
                LogUtils.i("", ">>>>>>onFailure" + result);
            }
        });
    }


    //商品列表
    public void GetGoods(final int categoryId, int pageNo) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("categoryId", categoryId);//商品分类Id，不传默认全部
        maps.put("pageNo", pageNo);//第几页，不传递默认第一页
        maps.put("pageSize", 15);//一页多少条，不传递默认10条
        HttpUtils.getInstance(getActivity()).postAsnyRequest(NetworkAddress.Goods, HttpUtils.getMaps(maps), new ResponseUtils() {
            @Override
            public void onSucceed(String code, JSONObject request) {
                try {
                    LogUtils.i("", ">>>>>>list" + categoryId + request);
                    JSONArray dataList = JsonResult.getJSONArray(request, "dataList");
                    for (int i = 0; i < dataList.length(); i++) {
                        JSONObject jsonObject = dataList.getJSONObject(i);
                        try {
                            H2ShopItemBean h2ShopItemBean = (H2ShopItemBean) GsonUtils.getGsonData(H2ShopItemBean.class, jsonObject.toString());
                            lists.add(h2ShopItemBean);
                        } catch (Exception e) {
                            LogUtils.i("", ">>>>>>e" + e);
                        }
                    }
                } catch (Exception e) {
                    LogUtils.i("", ">>>>>>e" + e);
                }
                hander.sendEmptyMessage(200);
            }

            @Override
            public void onFailure(String result) {
                LogUtils.i("", ">>>>>>onFailure" + result);
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        // 页面埋点
        StatService.onPageStart(getActivity(), "分类");
    }

    @Override
    public void onPause() {
        super.onPause();
        // 页面埋点
        StatService.onPageEnd(getActivity(), "分类");
    }


}
